<template>
  <div class="content-wrapper">

    <div class="content-container">
      <el-form label-width="auto" :inline="true" class="demo-form-inline">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="运单号" class="full-width">
              <el-input v-model="filters.trackingNumber" placeholder="请输入运单号" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出发地" class="full-width">
              <el-input v-model="filters.origin" placeholder="请输入出发地" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="目的地" class="full-width">
              <el-input v-model="filters.destination" placeholder="请输入目的地" class="full-width"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态" class="full-width">
              <el-select v-model="filters.state" placeholder="请选择状态" class="full-width">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="待确认" :value="'待确认'"></el-option>
                <el-option label="待运营商确认" :value="'待运营商确认'"></el-option>
                <el-option label="待配送" :value="'待配送'"></el-option>
                <el-option label="运输中" :value="'运输中'"></el-option>
                <el-option label="已送达" :value="'已送达'"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="类型" class="full-width">
              <el-select v-model="filters.customerType" placeholder="请选择类型" class="full-width">
                <el-option label="全部" :value="null"></el-option>
                <el-option label="货品" :value="0"></el-option>
                <el-option label="商品" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="预计到达时间" class="full-width">
              <el-date-picker
                  v-model="filters.departureDate"
                  type="daterange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  class="full-width">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item class="right full-width" label=" ">
              <el-button-group class="full-width">
                <el-button icon="search" type="primary" plain @click="search" style="width: 50%">查询</el-button>
                <el-button icon="refresh" @click="resetFilters" style="width: 50%">重置</el-button>
              </el-button-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="divider"></div>

      <el-table :data="currentTableData"
                ref="table"
                style="width: 100%;
                flex: 1"
                :header-cell-style="{
                  backgroundColor: '#f5f7fa',
                  color: '#333',
                  fontWeight: 'bold',
                  textAlign: 'center',
                  padding: '10px 0'
                }"
                :cell-style="{
                  padding: '10px 0'
                }"
                @selection-change="updateSelection"
                :default-sort="{ prop: 'hireDate', order: 'descending' }">
        <el-table-column type="selection" :selectable="isSelectable" width="45"/>
        <el-table-column prop="trackingNumber" label="运输单号" width="130" fixed align="left">
          <template v-slot="scope">
            <el-link type="primary" @click="openDetailDialog(scope.row)">{{ scope.row.trackingNumber }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="origin" label="出发地" width="130" align="left"></el-table-column>
        <el-table-column prop="destination" label="目的地" width="130" align="left"></el-table-column>
        <el-table-column prop="customerType" label="货物类型" width="90" align="center">
          <template v-slot="scope">
            <el-tag
                :type="scope.row.customerType === 0 ? 'success' : scope.row.driverState === 1 ? 'warning' : 'danger'"
                disable-transitions>
              {{ scope.row.customerType === 0 ? '货品' : '商品' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="重量" width="90" align="right">
          <template v-slot="scope">
            <span>{{ scope.row.weight }}{{ scope.row.weightUnit }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="transportQuantity" label="数量" width="70" align="right"/>
        <el-table-column prop="departureDate" label="预计到货日期" sortable width="180">
          <template v-slot="scope">
            <span>{{ formatDate(scope.row.departureDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="下达日期" sortable width="180">
          <template v-slot="scope">
            <span>{{ formatDate(scope.row.generatedDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="配送单号" width="140">
          <template v-slot="scope">
            <span>{{ scope.row.deliveryId === null ? '暂无': scope.row.deliveryId }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" min-width="110">
          <template v-slot="scope">
            <el-tag
                :type="scope.row.state === '待确认' ? 'danger'
          : scope.row.state === '待运营商确认' ? 'warning'
          : scope.row.state === '待配送' ? 'info'
          : scope.row.state === '运输中' ? 'success'
          : 'primary'"
                disable-transitions>
              {{ scope.row.state }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="运费" width="100" align="right">
          <template v-slot="scope">
            <span>{{ scope.row.feeTemp }}元</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template v-slot="scope">
            <div style="display: flex; justify-content: center;">

              <template v-if="scope.row.state === '待确认'">
                <el-button @click="confirmAction(scope.row)" type="text" icon="pointer" style="font-size: 13px">确认
                </el-button>
                <el-button @click="openEditDialog(scope.row, true)" type="text" icon="EditPen" style="font-size: 13px">
                  修改
                </el-button>
              </template>
              <template v-else-if="scope.row.state === '待运营商确认'">
                <el-button @click="openEditDialog(scope.row, false)" type="text" style="font-size: 13px" icon="View">
                  查看修改请求
                </el-button>
              </template>
              <template v-else-if="scope.row.state === '运输中'">
                <el-button @click="startDelivery(scope.row)" type="text" style="font-size: 13px" icon="Van">配送
                </el-button>
                <el-button @click="changeAction(scope.row)" type="text" style="font-size: 13px" icon="ChatSquare">变更
                </el-button>
              </template>
              <template v-else-if="scope.row.state === '待配送'">
                <el-button @click="changeAction(scope.row)" type="text" style="font-size: 13px" icon="ChatSquare">变更
                </el-button>
              </template>
              <template v-else-if="scope.row.state === '已送达'">
                <el-button type="text" icon="SuccessFilled" style="font-size: 13px; color: green">订单已完成</el-button>
              </template>
            </div>
          </template>
        </el-table-column>

      </el-table>
      <div class="table-bottom">
        <div class="action-buttons">
          <el-button type="success" :disabled="!generateEnabled" plain icon="plus" @click="openGenerateDialog">
            {{ !generateEnabled ? "选择运输订单" : "生成配送订单" }}（{{ selectedOrders.length }}）
          </el-button>
        </div>
        <el-pagination
            background
            layout="total, prev, pager, next"
            :total="total"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @current-change="handleCurrentChange"
            class="fixed-pagination">
        </el-pagination>
      </div>


      <transport-detail-dialog v-model="detailDialogVisible" :order="selectedOrder"
                               @close="detailDialogVisible = false"/>

      <generate-dialog
          v-model="generateDialogVisible"
          :selected-orders="selectedOrders"
          @success="handleGenerateSuccess"
      />

      <el-dialog title="查看修改信息" v-model="editDialogVisible" width="50%"
                 style="border-radius: 12px;
        display: flex;
        flex-direction: column;
        margin: 0 !important;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        max-height: calc(100% - 30px);
        max-width: calc(100% - 30px);
        justify-content: center;"
                 @close="editDialogVisible = false;search()"
      >
        <div class="order-form-container">
          <div class="order-form-column">
            <div class="title">原信息</div>
            <el-form :model="selectedOrder">
              <el-form-item label="运费">
                <el-input-number v-model="selectedOrder.logisticsFee" style="width: 100%" disabled/>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="selectedOrder.remarks" rows="10" disabled/>
              </el-form-item>
            </el-form>
          </div>

          <div class="arrow-container">
            <span class="arrow">→</span>
          </div>

          <div class="order-form-column">
            <div class="title">新信息</div>
            <el-form :model="selectedOrder">
              <el-form-item label="运费">
                <el-input-number
                    v-model="selectedOrder.feeTemp"
                    min="0"
                    placeholder="请输入运费"    style="width: 100%"
                    :readonly="isFreightEdit"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="selectedOrder.tempRemarks" placeholder="请输入备注" rows="10" :readonly="isFreightEdit"/>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <template #footer>
          <el-button @click="editDialogVisible = false;search()">取消</el-button>
          <el-button type="primary" v-if="!isFreightEdit" @click="saveOrder">确认</el-button>
        </template>
      </el-dialog>

      <el-dialog title="变更预期到达时间" v-model="changeDialogVisible" width="50%"
                 style="border-radius: 12px;
        display: flex;
        flex-direction: column;
        margin: 0 !important;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        max-height: calc(100% - 30px);
        max-width: calc(100% - 30px);
        justify-content: center;">
        <el-form v-model="selectedOrder" label-width="120px">
          <el-form-item label="预计到达时间">
            <el-date-picker v-model="selectedOrder.departureDate" type="datetime"
                            placeholder="请选择预计到达时间"></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button @click="changeDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="changeOrder(selectedOrder)">保存</el-button>
        </div>
      </el-dialog>


    </div>
  </div>

</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage} from "element-plus";
import {
  addTransport,
  getTransportDetail,
  listTransport,
  deleteTransport,
  updateTransport,
  confirmTransport,
  updateArrivalTime
} from '@/api/delivery/transport.js';
import TransportDetailDialog from "@/views/delivery/transport/transportDetailDialog.vue";
import GenerateDialog from "@/views/delivery/transport/generateDialog.vue";

const filters = reactive({
  trackingNumber: '',
  origin: '',
  destination: '',
  departureDate: [],
  state: null,
  customerType: null,
});

const selectedOrder = ref({});
const isEdit = ref(false);

const currentTableData = ref([]);
const total = ref(0);
const pageSize = ref(7);
const currentPage = ref(1);

const dialogVisible = ref(false);

const openDialog = (order, edit) => {
  dialogVisible.value = true;
  isEdit.value = edit;
  selectedOrder.value = order || {};
};

const handleSave = async (OrderData) => {
  try {
    if (isEdit.value) {
      await updateTransport(OrderData);
    } else {
      await addTransport(OrderData);
    }

    dialogVisible.value = false;
    search();
  } catch (error) {
    console.error('保存失败:', error);
  }
};

const handleDelete = async (row) => {
  try {
    await deleteTransport(row.trackingNumber);
    if (currentTableData.value.length === 1 && currentPage.value > 1) {
      currentPage.value -= 1;
    }
    search();
  } catch (error) {
    console.error('删除失败:', error);
  }
};

const detailDialogVisible = ref(false);
const openDetailDialog = async (order) => {
  try {
    /*const response = await getTransportDetail(order);*/
    selectedOrder.value = order; // 这里要确保传递的是完整的订单对象
    detailDialogVisible.value = true; // 打开详情弹窗
  } catch (error) {
    ElMessage.error('获取订单详情失败');
  }
};

const formatDate = (value) => {
  if (!value) return '';
  const date = new Date(value);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const search = async () => {
  const query = {
    trackingNumber: filters.trackingNumber,
    origin: filters.origin,
    destination: filters.destination,
    state: filters.state,
    customerType: filters.customerType,
    startDate: filters.departureDate.length ? formatDate(filters.departureDate[0]) : null,
    endDate: filters.departureDate.length ? formatDate(filters.departureDate[1]) : null,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  try {
    const response = await listTransport(query);
    makeup = true;
    currentTableData.value = response.data;
    updateSelection();
    makeup = false;
    total.value = response.total;
  } catch (error) {
    ElMessage.error('获取运输订单信息失败');
    console.error('获取运输订单信息失败:', error);
  }
};

const selectedOrders = ref([]);

const selectedType = ref(null);

const generateEnabled = ref(false);

let makeup = false;
// 表格主选择框选中时触发

let updating = false;
const updateSelection = () => {
  if (updating) {
    return;
  }
  updating = true;
  for (const row of currentTableData.value) {
    if (row.state !== '待配送') {
      table.value.toggleRowSelection(row, false);
    }
  }
  const rows = table.value.getSelectionRows();
  console.log("makeup", makeup, "rows", rows);

  for (const row of rows) {
    selectedOrders.value.some((order) => {
      if (order.trackingNumber === row.trackingNumber) {
        return true;
      }
    }) || selectedOrders.value.push(row);
  }

  console.log("selectedOrders", selectedOrders.value);

  //筛选没被选中的订单
  const noneSelection = currentTableData.value.filter((row) => {
    return !rows.some((order) => {
      return order.trackingNumber === row.trackingNumber;
    });
  });
  console.log("noneSelection", noneSelection);
  if (makeup) {
    for (const row of noneSelection) {
      if (row.state ==='待配送' && selectedOrders.value.some((order) => {
        return order.trackingNumber === row.trackingNumber;
      })) {
        console.log("toggleRowSelection", row);
        nextTick(() => {
          setTimeout(() => {
            if (table.value) {
              table.value.toggleRowSelection(row, true);
            }
          }, 0);
        });
      }
    }
  } else {
    //如果SelectedOrder有没被选中的订单，就删除
    selectedOrders.value = selectedOrders.value.filter((order) => {
      return !noneSelection.some((row) => {
        return row.trackingNumber === order.trackingNumber;
      });
    });
  }

  console.log("selectedOrders", selectedOrders.value);


  selectedType.value = selectedOrders.value.length > 0 ? selectedOrders.value[0].customerType : null;
  generateEnabled.value = selectedOrders.value.length > 0;
  updating = false;
}

const changeDialogVisible = ref(false);
const changeAction = (row) => {
  selectedOrder.value = row;
  changeDialogVisible.value = true;
};

const changeOrder = async (order) => {
  try {
    await updateArrivalTime(order.trackingNumber, order.departureDate);
    ElMessage.success('变更预计到达时间成功');
    changeDialogVisible.value = false;
    search();
  } catch (error) {
    console.error('变更预计到达时间失败:', error);
  }


};


const isSelectable = (row) => {
  return (selectedType.value === null || row.customerType === selectedType.value) && row.state === '待配送';
};

const generateDialogVisible = ref(false);

const openGenerateDialog = () => {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning("请先选择运输订单！");
    return;
  }
  generateDialogVisible.value = true;
};

const handleGenerateSuccess = () => {
  selectedOrders.value = [];
  search();
};

const resetFilters = () => {
  filters.trackingNumber = '';
  filters.origin = '';
  filters.destination = '';
  filters.departureDate = [];
  filters.state = null;
  filters.customerType = null;
  currentPage.value = 1;
  search();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  search();
};

const confirmAction = async (row) => {
  if (row.state === '待确认') {
    row.logisticsFee = row.feeTemp;
    row.remarks = row.tempRemarks;
    try {
      await confirmTransport(row.trackingNumber);
      ElMessage.success('确认运输订单' + row.trackingNumber);
      search();
    } catch (error) {
      console.error('确认失败:', error);
    }
  }
};

const editDialogVisible = ref(false);
const originalFeeTemp = ref(0);
const isFreightEdit = ref(true);
const openEditDialog = (order, edit) => {
  isFreightEdit.value = !edit;
  selectedOrder.value = order;
  originalFeeTemp.value = order.feeTemp;
  editDialogVisible.value = true;
};

const saveOrder = async () => {
  try {
    if (selectedOrder.value.feeTemp === originalFeeTemp.value) {
      ElMessage.warning('运费未修改');
      return;
    }
    await updateTransport(selectedOrder.value, "edit");
    console.log(selectedOrder.value);
    editDialogVisible.value = false;
    ElMessage.success('修改' + selectedOrder.value.trackingNumber + '成功, 等待运营商确认！');
    await search();
  } catch (error) {
    console.error('保存失败:', error);
  }
};

const table = ref(null);
// 将当前行的选择框处于选中状态
const startDelivery = async (row) => {
  // 将当前行的选择框处于选中状态，添加至selectedOrders
  table.value.toggleRowSelection(row, true);

};


onMounted(() => {
  search();
});

</script>

<style scoped>
.order-form-container {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.order-form-column {
  width: 45%;
  padding: 20px;
  background-color: rgba(249, 249, 249, 0.63);
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
}

.arrow-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  margin: 20px 0;
  align-self: center;
}

.arrow {
  font-weight: bold;
  color: #409eff;
}

.el-container {
  height: 100%;
  width: 100%;
}

.content-wrapper {
  background-color: #f5f7fa;
  min-height: inherit;
  display: flex;
  height: calc(100vh - 84px);
}

.content-container {
  flex: 1;
  background-color: white;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06);
  width: calc(100% - 40px);
  box-sizing: border-box;
  border-radius: 8px;
  position: relative;
  display: flex;
  flex-direction: column;
  margin: 15px 20px;
}

.divider {
  height: 1px;
  background-color: #eaeaea;
  margin-top: 0;
  margin-bottom: 12px;
}

.dialog-footer {
  align-content: center;
  align-self: center;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.right-aligned {
  display: flex;
  justify-content: flex-end;
}

.el-segmented {
  width: 100%;
}

.el-form-item.right:deep(.el-form-item__content) {
  justify-content: end;
}

.demo-form-inline {
  display: flex;
  flex-wrap: wrap;
  background: white;
}

.full-width {
  width: 100%;
}

.table-bottom {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}

.fixed-pagination {
  margin-top: 20px;
}

</style>
